package com.laborer.PTSS.dao.impl;

import com.laborer.PTSS.dao.UserDao;
import com.laborer.PTSS.domain.User;
import com.laborer.PTSS.util.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * Created by fei on 2019/11/20.
 */
public class UserDaoImpl implements UserDao {

    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public User findByUsername(String username) {
        User user = null;
        try{
            // 1.定义sql
            String sql = "select * from tab_user where username = ?";
            // 2.执行sql
            user = template.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class),username);
        }catch (Exception e){

        }
        return user;
    }

    @Override
    public void save(User user) {
        // 1.定义sql
        String sql = "insert into tab_user(username,password,lastname,firstname,sex,telephone,email) "+
                "values(?,?,?,?,?,?,?)";
        // 2.执行sql
        template.update(sql,user.getUsername(),
                user.getPassword(),
                user.getLastname(),
                user.getFirstname(),
                user.getSex(),
                user.getTelephone(),
                user.getEmail()
        );
    }

    /**
     * 根据激活码查询用户对象
     * @param code
     * @return
     */
    @Override
    public User findByCode(String code) {
        User user = null;
        try {
            String sql = "select * from tab_user where code = ?";
            user = template.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class),code);
        }catch (DataAccessException e){
            e.printStackTrace();
        }

        return user;
    }

    /**
     * 根据用户名和密码查询的方法
     * @param username
     * @param password
     * @return
     */
    @Override
    public User findByUsernameAndPassword(String username, String password) {
        User user = null;
        try{
            // 1.定义sql
            String sql = "select * from tab_user where username = ? and password = ?";
            // 2.执行sql
            user = template.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class),username,password);
        }catch (Exception e){

        }
        return user;
    }

}
